
import datetime
from sanic import Request
from app.service.blackToken import BlackTokenService

# 白名单不用检查token
whiteList=["/user/login","/user/register","/common/captcha",
           "/common/captcha/phone","/test/index","/public/*"]

async def authRequestMiddleware(request:Request):
    from app.core.exception import ApiException
    from app.utils.JwtUtils import JwtUtils
    path=request.path
    now=datetime.datetime.now().timestamp()
    # if request.protocol.get_protocol().
    if path in whiteList:
        return
    for url in whiteList:
        if url.endswith("*"):
            if url[:-1] in path:
                return
    token=request.headers.get("x-token")
    if token==None or token=='':
        raise ApiException("当前链接未授权，请登录",code=3)
    BlackTokenService.checkToken(token)
    paylod=JwtUtils.decodeToken(token,options={"verify_exp":False})
    if paylod['exp']<now:
        BlackTokenService.addBlackToken(token)
        token=JwtUtils.createUserToken(paylod['userId'])
        request.headers['x-token'] = token
        request.headers.add('x-refresh-token',token)